package de.baumann.browser.fragments;

import android.annotation.SuppressLint;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.VideoView;

import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.sdk.WebView;

import org.jetbrains.annotations.NotNull;

import de.baumann.browser.R;
import de.baumann.browser.activitys.BookMarkAddHistoryActivity;
import de.baumann.browser.activitys.FeedBackActivity;
import de.baumann.browser.activitys.H5Activity;
import de.baumann.browser.activitys.MainActivity;
import de.baumann.browser.activitys.SettingActivity;
import de.baumann.browser.activitys.WebSiteActivity;
import de.baumann.browser.activitys.user.LoginActivity;
import de.baumann.browser.base.BaseOdinFragment;
import de.baumann.browser.base.BasePresenter;
import de.baumann.browser.db.Record;
import de.baumann.browser.db.RecordAction;
import de.baumann.browser.iview.IBaseView;
import de.baumann.browser.utils.Constants;
import de.baumann.browser.utils.ViewUtil;
import de.baumann.browser.views.widget.FloatSearchBar;
import de.baumann.browser.views.widget.FullscreenHolder;
import de.baumann.browser.views.dialog.MenuDialog;
import de.baumann.browser.web.OdinWebView;
import de.baumann.browser.web.WebUiController;

import static de.baumann.browser.utils.UserDataKt.isLogined;

/**
 * @author:
 * @date:2018/12/5 11:58
 * @discription: 加载网页
 */
public class WebSiteFragment extends BaseOdinFragment implements WebUiController, View.OnClickListener, MenuDialog.MenuClickListener {

    private FloatSearchBar mWebsiteSearchbar;
    private OdinWebView odinWebView;
    private ImageView mIvBack, mIvForward;
    private TextView mPagerNum;

    public static WebSiteFragment getWebSiteFragment(String content) {
        WebSiteFragment webSiteFragment = new WebSiteFragment();
        Bundle bundle = new Bundle();
        bundle.putString("content", content);
        webSiteFragment.setArguments(bundle);
        return webSiteFragment;
    }

    @Override
    public int getLayout() {
        return R.layout.fragment_website;
    }

    @Override
    public void initView(View view) {
        mWebsiteSearchbar = view.findViewById(R.id.websiteSearchbar);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mWebsiteSearchbar.getLayoutParams();
        layoutParams.setMargins(0, ViewUtil.getStatusBarHeight(mContext), 0, 0);
        mIvBack = view.findViewById(R.id.ivBack);
        mIvForward = view.findViewById(R.id.ivForward);
        mPagerNum = view.findViewById(R.id.tvPagerNum);
        mIvBack.setOnClickListener(this);
        mIvForward.setOnClickListener(this);
        view.findViewById(R.id.ivMenu).setOnClickListener(this);
        view.findViewById(R.id.ivHome).setOnClickListener(this);
        view.findViewById(R.id.flWindowsNum).setOnClickListener(this);
        mWebsiteSearchbar.mFloatSearchRefresh.setOnClickListener(view12 -> reload());
        odinWebView = view.findViewById(R.id.websiteContainer);
        odinWebView.setUiController(this);
    }

    @Override
    public void initData() {
        load(getArguments().getString("content"));
    }

    public OdinWebView getWebView() {
        return odinWebView;
    }

    public void load(String url) {
        odinWebView.loadUrl(url);
        mWebsiteSearchbar.setTitle(url);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (odinWebView != null) {
            odinWebView.onResume();
            odinWebView.resumeTimers();
        }
        setTabCount();
    }

    public void setTabCount() {
        if (mPagerNum != null) {
            int tabCount = ((WebSiteActivity) getActivity()).getTabCount();
            mPagerNum.setText(String.valueOf(tabCount));
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if (odinWebView != null) {
            odinWebView.onPause();
            odinWebView.pauseTimers();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (odinWebView != null) {
            odinWebView.destroy();
        }
    }

    @Override
    public void onPageStarted(WebView webView, Bitmap favicon) {
        mWebsiteSearchbar.setTitle(getText(R.string.loading));
    }

    @Override
    public void onPageFinished(String title, String url) {
        mWebsiteSearchbar.setTitle(title);
    }

    @Override
    public void onProgressChanged(int progress) {
        mWebsiteSearchbar.setprogress(progress);
    }

    @Override
    public void onReceivedTitle(String title) {
        mWebsiteSearchbar.setTitle(title);
    }

    @Override
    public void goBackEnable(boolean enable) {
        mIvBack.setEnabled(enable);
        if (enable) {
            mIvBack.setImageResource(R.drawable.ic_back);
        } else {
            mIvBack.setImageResource(R.drawable.ic_back_normal);
        }
    }

    @Override
    public void goForwardEnable(boolean enable) {
        mIvForward.setEnabled(enable);
        if (enable) {
            mIvForward.setImageResource(R.drawable.ic_forward);
        } else {
            mIvForward.setImageResource(R.drawable.ic_forward_normal);
        }
    }

    private View customView;
    private int originalOrientation;
    private FrameLayout fullscreenHolder;
    private VideoView videoView;
    private IX5WebChromeClient.CustomViewCallback customViewCallback;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    public void showCustomView(View view, IX5WebChromeClient.CustomViewCallback callback) {
        if (view == null) {
            return;
        }
        if (customView != null && callback != null) {
            callback.onCustomViewHidden();
            return;
        }

        customView = view;
        originalOrientation = getActivity().getRequestedOrientation();

        fullscreenHolder = new FullscreenHolder(mContext);
        fullscreenHolder.addView(
                customView,
                new FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT,
                        FrameLayout.LayoutParams.MATCH_PARENT
                ));

        FrameLayout decorView = (FrameLayout) getActivity().getWindow().getDecorView();
        decorView.addView(
                fullscreenHolder,
                new FrameLayout.LayoutParams(
                        FrameLayout.LayoutParams.MATCH_PARENT,
                        FrameLayout.LayoutParams.MATCH_PARENT
                ));

        customView.setKeepScreenOn(true);
        setCustomFullscreen(true);

        if (view instanceof FrameLayout) {
            if (((FrameLayout) view).getFocusedChild() instanceof VideoView) {
                videoView = (VideoView) ((FrameLayout) view).getFocusedChild();
                videoView.setOnErrorListener(new VideoCompletionListener());
                videoView.setOnCompletionListener(new VideoCompletionListener());
            }
        }
        customViewCallback = callback;
        getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    @Override
    public void hideCustomView() {
        if (customView == null || customViewCallback == null) {
            return;
        }

        FrameLayout decorView = (FrameLayout) getActivity().getWindow().getDecorView();
        if (decorView != null) {
            decorView.removeView(fullscreenHolder);
        }

        customView.setKeepScreenOn(false);
        setCustomFullscreen(false);

        fullscreenHolder = null;
        customView = null;
        if (videoView != null) {
            videoView.setOnErrorListener(null);
            videoView.setOnCompletionListener(null);
            videoView = null;
        }
        getActivity().setRequestedOrientation(originalOrientation);
    }

    private void setCustomFullscreen(boolean fullscreen) {
        View decorView = getActivity().getWindow().getDecorView();
        if (fullscreen) {
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN);
        } else {
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
    }


    @NotNull
    @Override
    public BasePresenter createPresenter() {
        return null;
    }

    @NotNull
    @Override
    public IBaseView createView() {
        return null;
    }

    @Override
    public void onClickLogin() {
//        if (!isLogined()) {
//            LoginActivity.Companion.startLoginActivity(getActivity());
//        }
    }

    private RecordAction action;
    @Override
    public void onClickAddBookmark() {
        action = new RecordAction(mContext);
        String url = odinWebView.getUrl();
        String title = odinWebView.getTitle();
        if (TextUtils.isEmpty(url)) {
            return;
        }
        action.open(true);
        if (action.checkBookmark(url)) {
            onError(getString(R.string.toast_entry_exists));
        } else {
            action.addBookmark(new Record(title, url, System.currentTimeMillis()));
            onError(getString(R.string.toast_add_bookmark_successful));
        }
        action.close();
    }

    @Override
    public void onClickHisttory() {
        BookMarkAddHistoryActivity.startBookMarkAddHistoryActivity(mContext);
    }

    @Override
    public void onClickRefresh() {
        odinWebView.reload();
    }

    @Override
    public void onClickSetting() {
        SettingActivity.Companion.startSettingActivity(mContext);
    }

    @Override
    public void onClickAbout() {
        H5Activity.startAboutOdinActivity(mContext, Constants.ABOUT_ODIN_URL);
    }

    @Override
    public void onClickFeedback() {
        if (isLogined()) {
            FeedBackActivity.Companion.startFeedBackActivity(mContext);
        } else {
            showLoginDialog();
        }
    }

    @Override
    public void onClickWindows() {
        ((WebSiteActivity) getActivity()).onWindowsClick();
    }

    @Override
    public void onClickDownload() {

    }

    private class VideoCompletionListener implements MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            return false;
        }

        @Override
        public void onCompletion(MediaPlayer mp) {
            hideCustomView();
        }
    }

    public String getUrl() {
        return odinWebView == null ? "" : odinWebView.getUrl();
    }

    public String getTitle() {
        return odinWebView == null ? "" : odinWebView.getTitle();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivMenu:
                MenuDialog menuDialog = new MenuDialog(mContext);
                menuDialog.setOnClickListener(WebSiteFragment.this);
                menuDialog.show();
                break;
            case R.id.ivBack:
                if (canGoBack()) {
                    goBack();
                } else {
                    getActivity().finish();
                }
                break;
            case R.id.ivForward:
                odinWebView.goForward();
                break;
            case R.id.ivHome:
                getActivity().finish();
                break;
            case R.id.flWindowsNum:
                ((WebSiteActivity) getActivity()).onWindowsClick();
                break;
            default:
        }
    }

    public void reload() {
        if (odinWebView != null) {
            odinWebView.reload();
        }
    }

    public boolean canGoBack() {
        return odinWebView.canGoBack();
    }

    public void goBack() {
        odinWebView.goBack();
    }

    @Override
    public boolean showBindEth() {
        return false;
    }
}
